<!-- src/components/SignUpManagement.vue (最终修正版) -->
<template>
  <div class="signup-management">
    <!-- 页面头部操作栏 -->
    <div class="page-header">
      <div class="header-left">
        <div class="filter-section">
          <div class="filter-group">
            <label>状态筛选：</label>
            <select v-model="filters.status" @change="loadSignups">
              <option value="">全部</option>
              <option value="upcoming">即将开始</option>
              <option value="ongoing">进行中</option>
              <option value="ended">已结束</option>
            </select>
          </div>
          <div class="filter-group">
            <label>课程筛选：</label>
            <select v-model="filters.courseId" @change="loadSignups">
              <option value="">全部课程</option>
              <option v-for="course in courses" :key="course.id" :value="course.id">
                {{course.name || course.title  }}
              </option>
            </select>
          </div>
          <!-- <div class="search-group">
            <input 
              type="text" 
              placeholder="搜索报名信息..." 
              v-model="searchKeyword"
              @keyup.enter="loadSignups"
            />
            <button class="search-btn" @click="loadSignups">
              <i class="icon-search"></i>
            </button>
          </div> -->
        </div>
      </div>
      <div class="header-right">
        <button class="btn btn-primary" @click="showCreateModal">
          <i class="icon-plus"></i>新建报名
        </button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      正在加载...
    </div>

    <!-- 数据表格 -->
    <div class="table-container" v-else>
      <table class="data-table">
        <thead>
          <tr>
            <!-- <th>报名ID</th> -->
            <th>课程名称</th>
            <th>教师</th>
            <!-- <th>培训机构</th> -->
            <th>开始时间</th>
            <th>结束时间</th>
            <th>容量</th>
            <th>已报名</th>
            <th>报名率</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="signup in signups" :key="signup.id">
            <!-- <td>{{ signup.id }}</td> -->
            <td class="course-title">{{ signup.course_title || '未知课程' }}</td>
            <td>{{ signup.teacher_name || '未知教师' }}</td>
            <!-- <td>{{ signup.agent_name || '未知机构' }}</td> -->
            <td>{{ formatDate(signup.start_date) }}</td>
            <td>{{ formatDate(signup.end_date) }}</td>
            <td>{{ signup.max_capacity }}</td>
            <td>
              <span class="enrollment-count" @click="viewEnrollments(signup.id)">
                {{ signup.current_enrollment_count || 0 }}
              </span>
            </td>
            <td>
              <div class="progress-bar">
                <div 
                  class="progress-fill" 
                  :style="`width: ${getEnrollmentRate(signup)}%`"
                ></div>
                <span class="progress-text">{{ getEnrollmentRate(signup) }}%</span>
              </div>
            </td>
            <td>
              <div class="action-buttons">
                <!-- <button class="btn-icon" @click="viewDetails(signup.id)" title="查看详情">
                  <i class="icon-eye"></i>
                </button> -->
                <button class="btn-icon" @click="editSignup(signup)" title="编辑">
                  <i class="icon-edit"></i>
                </button>
                <button class="btn-icon" @click="viewEnrollments(signup.id)" title="报名记录">
                  <i class="icon-list"></i>
                </button>
                <button class="btn-icon btn-danger" @click="deleteSignup(signup.id)" title="删除">
                  <i class="icon-trash"></i>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 空状态 -->
      <div v-if="signups.length === 0" class="empty-state">
        <div class="empty-icon">📝</div>
        <div class="empty-text">暂无报名记录</div>
        <button class="btn btn-primary" @click="showCreateModal">
          创建第一个报名
        </button>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="totalCount > 0">
      <div class="pagination-info">
        共 {{ totalCount }} 条记录，第 {{ currentPage }} / {{ totalPages }} 页
      </div>
      <div class="pagination">
        <button 
          class="page-btn" 
          :disabled="!hasPrev" 
          @click="changePage(currentPage - 1)"
        >
          上一页
        </button>
        <span class="page-numbers">
          <button 
            v-for="page in getPageNumbers()" 
            :key="page"
            class="page-btn"
            :class="{ active: page === currentPage }"
            @click="changePage(page)"
          >
            {{ page }}
          </button>
        </span>
        <button 
          class="page-btn" 
          :disabled="!hasNext" 
          @click="changePage(currentPage + 1)"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 创建/编辑模态框 -->
    <div class="modal-overlay" v-if="showModal" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditing ? '编辑报名' : '新建报名' }}</h3>
          <button class="close-btn" @click="closeModal">
            <i class="icon-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveSignup">
            <div class="form-group">
              <label>课程 *</label>
              <select v-model="signupForm.course_id" required>
                <option value="">请选择课程</option>
                <option v-for="course in courses" :key="course.id" :value="course.id">
                  {{ course.name || course.title }}
                </option>
              </select>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>开始时间 *</label>
                <input type="datetime-local" v-model="signupForm.start_date" required />
              </div>
              <div class="form-group">
                <label>结束时间 *</label>
                <input type="datetime-local" v-model="signupForm.end_date" required />
              </div>
            </div>
            <div class="form-group">
              <label>最大容量 *</label>
              <input type="number" v-model="signupForm.max_capacity" min="1" required />
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
          <button type="submit" class="btn btn-primary" @click="saveSignup">
            {{ isEditing ? '更新' : '创建' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 报名记录查看模态框 -->
    <div class="modal-overlay" v-if="showEnrollmentModal" @click="closeEnrollmentModal">
      <div class="modal large" @click.stop>
        <div class="modal-header">
          <h3>报名记录</h3>
          <button class="close-btn" @click="closeEnrollmentModal">
            <i class="icon-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div v-if="enrollments.length === 0" class="empty-state">
            <div class="empty-text">暂无报名记录</div>
          </div>
          <table v-else class="data-table">
            <thead>
              <tr>
                <th>学员姓名</th>
                <th>联系方式</th>
                <th>报名时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="enrollment in enrollments" :key="enrollment.id">
                <td>{{ enrollment.student_name || '未知学员' }}</td>
                <td>{{ enrollment.student_phone || '未知' }}</td>
                <td>{{ formatDate(enrollment.signup_time) }}</td>
                <td>
                  <button class="btn-icon btn-danger" @click="cancelEnrollment(enrollment.id)">
                    取消报名
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { signupAPI, courseAPI } from '@/services/api'

const router = useRouter()

// 响应式数据
const signups = ref([])
const courses = ref([])
const enrollments = ref([])
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')
const showModal = ref(false)
const showEnrollmentModal = ref(false)
const isEditing = ref(false)
const loading = ref(false)

// 筛选条件
const filters = reactive({
  status: '',
  courseId: ''
})

// 表单数据
const signupForm = reactive({
  course_id: '',
  start_date: '',
  end_date: '',
  max_capacity: ''
})

// 计算属性
const totalPages = computed(() => Math.ceil(totalCount.value / pageSize.value))
const hasNext = computed(() => currentPage.value < totalPages.value)
const hasPrev = computed(() => currentPage.value > 1)

// 计算报名率
const getEnrollmentRate = (signup) => {
  if (!signup.max_capacity || signup.max_capacity === 0) return 0
  const rate = Math.round((signup.current_enrollment_count / signup.max_capacity) * 100)
  return Math.min(rate, 100) // 确保不超过100%
}

// 加载课程列表（用于下拉选择）
const loadCourses = async () => {
  try {
    console.log('开始加载课程列表...')
    const result = await courseAPI.getCourses({ limit: 1000 })
    console.log('课程API响应:', result)
    courses.value = result.items || []
    console.log('课程列表加载完成，共', courses.value.length, '条')
  } catch (error) {
    console.error('加载课程列表失败:', error)
    courses.value = []
  }
}

// 加载报名数据
const loadSignups = async () => {
  try {
    loading.value = true
    console.log('开始加载报名列表...')
    
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      ...(filters.status && { status: filters.status }),
      ...(filters.courseId && { course_id: filters.courseId })
    }
    console.log('报名API请求参数:', params)

    const data = await signupAPI.getSignups(params)
    console.log('报名API响应:', data)
    
    signups.value = data.items || []
    totalCount.value = data.total || 0
    
    console.log('报名列表加载完成，共', signups.value.length, '条')
  } catch (error) {
    console.error('加载报名列表失败:', error)
    signups.value = []
    totalCount.value = 0
  } finally {
    loading.value = false
  }
}

const showCreateModal = () => {
  isEditing.value = false
  resetForm()
  showModal.value = true
}

const editSignup = (signup) => {
  isEditing.value = true
  Object.assign(signupForm, {
    id: signup.id,
    course_id: signup.course_id,
    start_date: formatDateForInput(signup.start_date),
    end_date: formatDateForInput(signup.end_date),
    max_capacity: signup.max_capacity
  })
  showModal.value = true
}

// 格式化日期为input[datetime-local]需要的格式
const formatDateForInput = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day}T${hours}:${minutes}`
}

const saveSignup = async () => {
  try {
    if (isEditing.value) {
      await signupAPI.updateSignup(signupForm.id, signupForm)
    } else {
      await signupAPI.createSignup(signupForm)
    }
    
    closeModal()
    await loadSignups()
    alert(isEditing.value ? '更新成功' : '创建成功')
  } catch (error) {
    console.error('保存失败:', error)
    alert(`操作失败: ${error.response?.data?.detail || error.message}`)
  }
}

const deleteSignup = async (id) => {
  if (!confirm('确定要删除这个报名吗？删除后无法恢复。')) return

  try {
    await signupAPI.deleteSignup(id)
    await loadSignups()
    alert('删除成功')
  } catch (error) {
    console.error('删除失败:', error)
    alert(`删除失败: ${error.response?.data?.detail || error.message}`)
  }
}

const viewEnrollments = async (signupId) => {
  try {
    const data = await signupAPI.getEnrollments({ signup_id: signupId })
    enrollments.value = data.items || []
    showEnrollmentModal.value = true
  } catch (error) {
    console.error('加载报名记录失败:', error)
    enrollments.value = []
    showEnrollmentModal.value = true
  }
}

const cancelEnrollment = async (enrollmentId) => {
  if (!confirm('确定要取消这个报名吗？')) return

  try {
    await signupAPI.cancelEnrollment(enrollmentId)
    
    // 重新加载当前的报名记录
    if (enrollments.value.length > 0) {
      const signupId = enrollments.value[0].signup_id
      await viewEnrollments(signupId)
    }
    // 重新加载报名列表以更新统计数据
    await loadSignups()
    alert('取消报名成功')
  } catch (error) {
    console.error('取消报名失败:', error)
    alert(`取消报名失败: ${error.response?.data?.detail || error.message}`)
  }
}

const viewDetails = (id) => {
  router.push(`/signups/${id}`)
}

const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return
  currentPage.value = page
  loadSignups()
}

const getPageNumbers = () => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
}

const closeModal = () => {
  showModal.value = false
  resetForm()
}

const closeEnrollmentModal = () => {
  showEnrollmentModal.value = false
  enrollments.value = []
}

const resetForm = () => {
  Object.assign(signupForm, {
    course_id: '',
    start_date: '',
    end_date: '',
    max_capacity: ''
  })
}

const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 生命周期
onMounted(async () => {
  console.log('SignUpManagement 组件挂载')
  await loadCourses() // 加载课程列表（用于下拉选择）
  await loadSignups() // 加载报名列表
})
</script>

<style scoped>
.signup-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.filter-section {
  display: flex;
  gap: 16px;
  align-items: center;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-size: 14px;
  color: #374151;
  white-space: nowrap;
}

.filter-group select {
  padding: 6px 12px;
  border: 1px solid #D1D5DB;
  border-radius: 4px;
  font-size: 14px;
  min-width: 120px;
}

.search-group {
  display: flex;
  align-items: center;
}

.search-group input {
  padding: 6px 12px;
  border: 1px solid #D1D5DB;
  border-radius: 4px 0 0 4px;
  font-size: 14px;
  width: 200px;
}

.search-btn {
  padding: 6px 12px;
  background: #4F46E5;
  color: white;
  border: 1px solid #4F46E5;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-primary {
  background: #4F46E5;
  color: white;
}

.btn-secondary {
  background: #6B7280;
  color: white;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #6B7280;
  font-size: 16px;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #E5E7EB;
}

.data-table th {
  background: #F9FAFB;
  font-weight: 600;
  color: #374151;
  font-size: 14px;
}

.course-title {
  font-weight: 500;
  color: #1F2937;
}

.enrollment-count {
  color: #4F46E5;
  cursor: pointer;
  text-decoration: underline;
  font-weight: 500;
}

.enrollment-count:hover {
  color: #3730A3;
}

.progress-bar {
  position: relative;
  background: #E5E7EB;
  border-radius: 4px;
  height: 20px;
  min-width: 80px;
}

.progress-fill {
  background: #4F46E5;
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s;
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 10px;
  color: #374151;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 4px;
}

.btn-icon {
  padding: 6px;
  border: none;
  background: none;
  border-radius: 4px;
  cursor: pointer;
  color: #6B7280;
  transition: all 0.2s;
}

.btn-icon:hover {
  background: #F3F4F6;
  color: #374151;
}

.btn-icon.btn-danger:hover {
  background: #FEE2E2;
  color: #DC2626;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #6B7280;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 0 20px;
}

.pagination-info {
  font-size: 14px;
  color: #6B7280;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-btn {
  padding: 6px 12px;
  border: 1px solid #D1D5DB;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #374151;
}

.page-btn:hover:not(:disabled) {
  background: #F3F4F6;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-btn.active {
  background: #4F46E5;
  color: white;
  border-color: #4F46E5;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  box-shadow: 0 10px 25px rgba(0,0,0,0.2);
  max-width: 500px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal.large {
  max-width: 800px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #E5E7EB;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #1F2937;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #6B7280;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
}

.close-btn:hover {
  background: #F3F4F6;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #E5E7EB;
}

.form-group {
  margin-bottom: 16px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.form-group label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 4px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #D1D5DB;
  border-radius: 4px;
  font-size: 14px;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #4F46E5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

/* 图标样式 */
.icon-plus::before { content: "➕"; }
.icon-search::before { content: "🔍"; }
.icon-eye::before { content: "👁️"; }
.icon-edit::before { content: "✏️"; }
.icon-list::before { content: "📋"; }
.icon-trash::before { content: "🗑️"; }
.icon-times::before { content: "✖️"; }
</style>